import { profile } from '@/utils/decorators';
import { $render, Logger } from '@/utils/logger';
import { runErrorMapped } from '@/utils/wrapper';

type CommandProcessor = (mainArg: string, leadingArgs?: string[]) => string;

const commands: Record<string, CommandProcessor> = {};

export const register = (command: string, processor: CommandProcessor) => {
    commands[command] = processor;
}

export const reject = (message = '未知子指令') => {
    return $render(message, ConsoleColor.red);
}


export class CommandInvoker {

    static invoke(tokens: string[]) {
        return runErrorMapped(() => {
            const tBegin = Game.cpu.getUsed();
            const fn = commands[tokens[0]];
            if (!fn) {
                return $render(`执行失败：未知指令 ${tokens[0]}`, ConsoleColor.red);
            }
            const result = fn(tokens[1], tokens.slice(2));
            const tUsed = Game.cpu.getUsed() - tBegin;
            Logger.info(`执行耗时：${tUsed.toFixed(2)} cpu`, 'invoke');
            return result;
        });
    }
}